Flow
is the Kotlin approach for handling a "cold stream" of items, where the
work to build the items only happens once something has subscribed to the stream.
A simple way to create a Flow
is to use the flow()
top-level function. You
provide a lambda expression, and it calls emit()
for every item that should
be placed into the stream. Here, we emit a series of random numbers, with a delay
between each.
A simple way to consume a Flow
is to call collect()
. This takes a lambda
expression, and it is passed each emitted item from the Flow
. collect()
is a suspend
function, so we need to call collect()
from inside of another
suspend
function or from a coroutine builder, such as launch()
.
You can learn more about this in:
Tags: